package org.bdware.doip.core.model.digitalObject;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.bdware.doip.core.utils.DoipGson;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class DigitalObject {
    public String id;
    public DoType type;
    public JsonObject attributes;
    public List<Element> elements;
    static final String UUID_KEY = "UUID";

    public DigitalObject(String id, DoType type) {
        this.id = id;
        this.type = type;
    }

    public void setAttributes(JsonObject data) {
        attributes = data;
    }

    /**
     * A convenience method that sets an attribute on the object.
     *
     * @param name the name of the attribute
     * @param att  the value to set as a String
     */
    public void addAttribute(String name, String att) {
        if (attributes == null) {
            attributes = new JsonObject();
        }
        attributes.addProperty(name, att);
    }

    public UUID getUUID() {
        if (attributes == null) return null;
        return attributes.has(UUID_KEY) ? UUID.fromString(attributes.get(UUID_KEY).getAsString()) : null;
    }

    public void setUUID(UUID uuid) {
        addAttribute(UUID_KEY, uuid.toString());
    }

    public void addAttribute(String name, Number att) {
        if (attributes == null) {
            attributes = new JsonObject();
        }
        attributes.addProperty(name, att);
    }

    public void addAttribute(String name, JsonElement att) {
        if (attributes == null) {
            attributes = new JsonObject();
        }
        attributes.add(name, att);
    }

    public void addElements(Element e) {
        if (this.elements == null) {
            this.elements = new ArrayList<>();
        }
        this.elements.add(e);
    }

    public boolean isSigned() {
        if (attributes != null && attributes.has("isSigned")) {
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        if (this.elements != null)
            for (Element e : this.elements
            ) {
                if (e.getData() != null)
                    e.dataString = new String(e.getData());
            }
        return DoipGson.getDoipGson().toJson(this);
    }

    public void needSign() {
        addAttribute("isSigned", "true");
    }
}
